import os
import glob,commands
from texWriter import texWriter

class postProccesor:
    def __init__(self,dir):
        self.dir = dir
        
    def malibuProcces(self):
        outFile = glob.glob(self.dir + "/*.out")[0]
        os.system('evaluate <' + outFile + '>' + self.dir + '/basic.eval')
        plots = ['roc','spr']
        self.doPlots(plots, outFile)
        
    def doPlots(self,pl,outFile):
        currDir = os.getcwd()
        os.chdir(self.dir)
        for p in pl:    
            os.system('evaluate ' + p + '<' + outFile + '>' + p+ '.plot')
            os.system('gnuplot ' + p +'.plot >' + p +'.png')
        os.chdir(currDir)
    
    def doExperimentReport(self,exp):
        name = exp.name + '.tex'
        file = open(self.dir + '/' + name,'w')
        file.write('\documentclass[10pt]{article}'+'\n')
        file.write('\\usepackage[paper=letterpaper,\
            marginparwidth=1.2in,     \
            marginparsep=.05in,       \
            margin=1in]{geometry} \n')
        file.write("\\title{Experiment: " + self.tStr(exp.name) + "}\n")
        file.writelines(['\\author{Malibu-glue} \n','\\begin{document} \n', '\maketitle \n'])
        file.write('\\paragraph{Describtion:}' + exp.desc + '\n')
        file.write('\\paragraph{Time:}' + self.tStr(exp.startTime) + ' \\textit{to} ' + self.tStr(exp.stopTime) + '\n')
        tableList = self.allTable()
        for s in tableList:
            file.write('\\input{' + s +'} \n')
        file.write('\\end{document} \n')
        file.close()
        curDir = os.curdir
        os.chdir(self.dir)
        failure, res = commands.getstatusoutput('latex ' + name)
        os.chdir(curDir)
    
    #make into valid tex string
    def tStr(self,st):
        return st.replace('_',' ')
    
    # print
    def allTable(self):
        myFiles = []
        os.path.walk(self.dir, self.getPattern , myFiles)
        lines = []
        for s in [m[0] for m in myFiles]:
            file = open(s,'r')
            ll = file.readlines()
            lines.append(ll[1].split())
            file.close()
        writer  = texWriter()
        writer.writeTexTable(ll[0].split(),lines, self.dir +'/masterTable.tex')
        writer.writeSortedTables(ll[0].split(),lines, self.dir +'/algSort.tex', 0)
        writer.writeSortedTables(ll[0].split(),lines, self.dir +'/datasetSort.tex', 1)
        writer.writeSortedTables(ll[0].split(),lines, self.dir +'/validMode.tex', 2)
        return ['masterTable', 'algSort','datasetSort', 'validMode']
                   
    def getPattern(self,arg,dirname,files):
        l = glob.glob(dirname + '/*.eval')
        if len(l)>0:
            arg.append(l)